package codetop.microsoft.T25;

import util.ListNode;

/**
 * @Author: 18362
 * @Create: 2022-08-17 8:32:01 星期三
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        int n = 1;
        ListNode p = head;
        while (p != null && n < k) {
            p = p.next;
            n++;
        }
        if (p == null)
            return head;
        ListNode tail = reverseKGroup(p.next, k);
        p.next = tail;
        return reverse(head, k);
    }

    private ListNode reverse(ListNode head, int k) {
        if (head == null || k <= 1)
            return head;
        ListNode tHead = reverse(head.next, k - 1);
        ListNode tail = head.next;
        head.next = tail.next;
        tail.next = head;
        return tHead;
    }
}